﻿using System.Collections.Generic;
using Cms.Domain;
using Cms.Domain.RepositoryInterfaces;
using NHibernate;
using NHibernate.Criterion;

namespace Cms.Data
{
    public class UserRepository : BaseRepository, IUserRepository
    {
        public UserRepository()
        {
        }

        public UserRepository(ISession session)
            : base(session)
        {
        }

        #region IUserRepository Members

        public IList<UserGroup> GetUserGroups()
        {
            return Session.CreateCriteria(typeof(UserGroup))
                .AddOrder(NHibernate.Criterion.Order.Asc("Name"))
                .List<UserGroup>();
        }
        
        public void DeleteUserGroup(int id)
        {
            DeleteHql("from UserGroup where Id = " + id, "UserRepository.DeleteUserGroup");
        }

        public UserGroup GetUserGroup(int id)
        {
            return Session.Get<UserGroup>(id);
        }

        public void SaveUserGroup(UserGroup group)
        {
            SaveEntity(group, "UserRepository.SaveUserGroup");
        }

        public void SaveUser(User user)
        {
            SaveEntity(user, "UserRepository.SaveUser");
        }

        public bool UserGroupNameExists(string name, int id)
        {
            string hql = "from UserGroup ug where ug.Name = :name";
            if (id > 0)
                hql += " and ug.ID <> " + id;
            IList<UserGroup> groups = Session.CreateQuery(hql)
                .SetString("name", name)
                .List<UserGroup>();
            return groups.Count > 0;
        }

        public User GetUser(int id)
        {
            return Session.Get<User>(id);
        }

        public User GetUser(string username, string password)
        {
            string hql = "from User u where u.Username = :username and u.Password = :password";
            IList<User> users = Session.CreateQuery(hql)
                .SetString("username", username)
                .SetString("password", password)
                .SetCacheable(true)
                .List<User>();
            return users.Count == 1 ? users[0] : null;
        }

        public void DeleteUser(int id)
        {
            DeleteHql("from User where Id = " + id, "UserRepository.DeleteUser");
        }

        public IList<User> SearchUsers()
        {
            string hql = "from User u";
            IList<User> users = Session.CreateQuery(hql)
                .SetCacheable(true)
                .List<User>();
            return users;
            
        }

        #endregion
    }
}